/**
 * 游戏逻辑处理类
 * 包含游戏的核心逻辑，如移动、事件处理等
 */
export default class GameLogic {
  /**
   * 处理玩家落地事件
   * @param {Object} gameState - 游戏状态
   * @param {Function} showEventMessage - 显示事件消息的回调函数
   * @param {Function} handleBankruptcy - 处理破产的回调函数
   * @param {Function} nextTurn - 进入下一回合的回调函数
   */
  static handlePlayerLanding(gameState, showEventMessage, handleBankruptcy, nextTurn) {
    // 如果玩家还在移动中，不处理落地事件
    if (gameState.isMoving) return;
    
    const player = gameState.players[gameState.currentPlayerIndex];
    const cell = gameState.boardCells[player.position];
    
    // 短暂延迟后再显示弹窗，确保动画完成
    setTimeout(() => {
      switch (cell.type) {
        case 'property':
          GameLogic.handlePropertyCell(cell, gameState, showEventMessage, handleBankruptcy, nextTurn);
          break;
        case 'chance':
          GameLogic.handleChanceCell(gameState, showEventMessage);
          break;
        case 'tax':
          GameLogic.handleTaxCell(cell, gameState, showEventMessage, handleBankruptcy);
          break;
        case 'go-to-jail':
          GameLogic.handleGoToJailCell(gameState, showEventMessage, nextTurn);
          break;
        case 'transport':
        case 'utility':
          GameLogic.handlePropertyCell(cell, gameState, showEventMessage, handleBankruptcy, nextTurn); // 同样处理为财产
          break;
        default:
          // 其他格子不做特殊处理，直接进入下一回合
          nextTurn();
      }
    }, 300); // 300毫秒延迟，确保动画完成
  }
  
  /**
   * 处理地产格子
   */
  static handlePropertyCell(cell, gameState, showEventMessage, handleBankruptcy, nextTurn) {
    const player = gameState.players[gameState.currentPlayerIndex];
    
    if (cell.owner === null) {
      // 无人拥有，可以购买
      if (player.money >= cell.price) {
        showEventMessage(
          '购买机会', 
          `是否购买${cell.name}？价格：${cell.price}元`, 
          [
            { text: '购买', action: 'buy', cell: cell },
            { text: '放弃', action: 'pass' }
          ]
        );
      } else {
        // 钱不够，直接跳过
        showEventMessage(
          '资金不足', 
          `你没有足够的资金购买${cell.name}`, 
          [{ text: '确定', action: 'confirm' }]
        );
        nextTurn();
      }
    } else if (cell.owner !== player.id) {
      // 需要支付租金
      const rent = cell.rent;
      if (player.money >= rent) {
        player.money -= rent;
        
        // 找到房主并支付租金
        const owner = gameState.players.find(p => p.id === cell.owner);
        if (owner) {
          owner.money += rent;
        }
        
        showEventMessage(
          '支付租金', 
          `你需要支付${rent}元租金给玩家${cell.owner}`, 
          [{ text: '确定', action: 'confirm' }]
        );
      } else {
        // 破产处理
        handleBankruptcy(player);
      }
    } else {
      // 自己的地产，直接进入下一回合
      nextTurn();
    }
  }
  
  /**
   * 处理机会格子
   */
  static handleChanceCell(gameState, showEventMessage) {
    // 随机抽取一张机会卡
    const cardIndex = Math.floor(Math.random() * gameState.chanceCards.length);
    const card = gameState.chanceCards[cardIndex];
    
    showEventMessage(card.title, card.description, card.actions);
  }
  
  /**
   * 处理税收格子
   */
  static handleTaxCell(cell, gameState, showEventMessage, handleBankruptcy) {
    const player = gameState.players[gameState.currentPlayerIndex];
    
    if (player.money >= cell.price) {
      player.money -= cell.price;
      showEventMessage(
        '支付税款', 
        `你需要支付${cell.price}元的税款`, 
        [{ text: '确定', action: 'confirm' }]
      );
    } else {
      // 破产处理
      handleBankruptcy(player);
    }
  }
  
  /**
   * 处理进监狱格子
   */
  static handleGoToJailCell(gameState, showEventMessage, nextTurn) {
    const player = gameState.players[gameState.currentPlayerIndex];
    
    // 找到监狱的位置
    const jailIndex = gameState.boardCells.findIndex(cell => cell.type === 'jail');
    if (jailIndex !== -1) {
      player.position = jailIndex;
      showEventMessage(
        '进监狱', 
        '你被送进了监狱，暂停一回合', 
        [{ text: '确定', action: 'confirm' }]
      );
    }
    
    nextTurn();
  }
  
  /**
   * 处理事件动作
   */
  static handleEventAction(action, gameState, callbacks) {
    const { 
      showEventMessage, 
      nextTurn, 
      movePlayer, 
      buyProperty, 
      handleBankruptcy,
      initiatePropertyExchange,
      handlePropertyExchange,
      handleSelectOwnProperty,
      completePropertyExchange,
      autoLogin
    } = callbacks;
    
    switch (action.action) {
      case 'autoLogin':
        // 处理自动登录动作
        autoLogin();
        return; // 不进入下一回合
        
      case 'buy':
        buyProperty(action.cell);
        break;
      case 'pass':
        // 放弃购买，直接进入下一回合
        nextTurn();
        break;
      case 'collect': {
        // 收取金钱
        gameState.players[gameState.currentPlayerIndex].money += action.amount;
        nextTurn();
        break;
      }
      case 'pay': {
        // 支付金钱
        const player = gameState.players[gameState.currentPlayerIndex];
        
        // 检查是否有免租金特权
        if (gameState.playerSpecialStatus[player.id].rentImmunity) {
          gameState.playerSpecialStatus[player.id].rentImmunity = false;
          showEventMessage(
            '免租金特权', 
            '你使用了免租金特权，无需支付费用！', 
            [{ text: '太好了', action: 'confirm' }]
          );
        } else if (player.money >= action.amount) {
          player.money -= action.amount;
          nextTurn();
        } else {
          handleBankruptcy(player);
        }
        break;
      }
      case 'birthday': {
        // 生日，从每个其他玩家那里收取礼金
        const birthdayPlayer = gameState.players[gameState.currentPlayerIndex];
        let totalGift = 0;
        
        gameState.players.forEach(p => {
          if (p.id !== birthdayPlayer.id && p.money > 0) {
            const gift = Math.min(p.money, action.amount);
            p.money -= gift;
            totalGift += gift;
          }
        });
        
        birthdayPlayer.money += totalGift;
        
        // 显示收到礼金的消息
        if (totalGift > 0) {
          showEventMessage(
            '收到礼金', 
            `你从其他玩家那里收到了${totalGift}元礼金！`, 
            [{ text: '太棒了', action: 'confirm' }]
          );
        } else {
          nextTurn();
        }
        break;
      }
      case 'move':
        // 移动指定步数
        movePlayer(gameState.currentPlayerIndex, action.steps);
        // 注意：handlePlayerLanding 会在移动动画完成后自动调用
        break;
      case 'teleport': {
        // 直接传送到指定位置
        const teleportPlayer = gameState.players[gameState.currentPlayerIndex];
        const oldPosition = teleportPlayer.position;
        
        // 添加传送动画效果
        gameState.isMoving = true;
        setTimeout(() => {
          teleportPlayer.position = action.position;
          
          // 如果有奖励，则添加
          if (action.bonus) {
            teleportPlayer.money += action.bonus;
            callbacks.showFloatingText(`+${action.bonus}元`, 'money');
          }
          
          callbacks.showFloatingText(`传送到${gameState.boardCells[action.position].name}!`, 'teleport');
          
          // 短暂延迟后结束动画效果
          setTimeout(() => {
            gameState.isMoving = false;
            // 处理落地事件
            GameLogic.handlePlayerLanding(gameState, showEventMessage, handleBankruptcy, nextTurn);
          }, 500);
        }, 500);
        break;
      }
      case 'randomMove': {
        // 随机移动步数
        const randomSteps = Math.floor(Math.random() * 
          (action.maxSteps - action.minSteps + 1)) + action.minSteps;
        
        showEventMessage(
          '随机移动', 
          `掷骰子结果：移动${randomSteps}步`, 
          [{ text: '开始移动', action: 'move', steps: randomSteps }]
        );
        break;
      }
      case 'randomTeleport': {
        // 随机传送到棋盘上的一个位置
        const boardSize = gameState.boardCells.length;
        const currentPos = gameState.players[gameState.currentPlayerIndex].position;
        
        // 生成一个不同于当前位置的随机位置
        let randomPosition;
        do {
          randomPosition = Math.floor(Math.random() * boardSize);
        } while (randomPosition === currentPos);
        
        showEventMessage(
          '随机传送', 
          `你将被传送到${gameState.boardCells[randomPosition].name}`, 
          [{ text: '传送', action: 'teleport', position: randomPosition }]
        );
        break;
      }
      case 'propertyBonus': {
        // 所有地产增值
        const currentPlayer = gameState.players[gameState.currentPlayerIndex];
        let propertyCount = 0;
        
        gameState.boardCells.forEach(cell => {
          if (cell.owner === currentPlayer.id) {
            cell.rent += action.amount;
            propertyCount++;
          }
        });
        
        if (propertyCount > 0) {
          showEventMessage(
            '地产升值', 
            `你的${propertyCount}处地产每处增值${action.amount}元！`, 
            [{ text: '太好了', action: 'confirm' }]
          );
        } else {
          showEventMessage(
            '没有地产', 
            '你没有任何地产，无法享受升值福利。', 
            [{ text: '真遗憾', action: 'confirm' }]
          );
        }
        break;
      }
      case 'extraTurn':
        // 获得额外回合
        gameState.playerSpecialStatus[gameState.players[gameState.currentPlayerIndex].id].extraTurn = true;
        showEventMessage(
          '额外回合', 
          '你获得了一个额外回合！在当前回合结束后，你将再次行动。', 
          [{ text: '太棒了', action: 'confirm' }]
        );
        break;
      case 'getRentImmunity':
        // 获得免租金特权
        gameState.playerSpecialStatus[gameState.players[gameState.currentPlayerIndex].id].rentImmunity = true;
        showEventMessage(
          '免租金特权', 
          '你获得了一次免租金特权！下次需要支付租金时将自动使用。', 
          [{ text: '太好了', action: 'confirm' }]
        );
        break;
      case 'propertyExchange':
        // 财产交换功能
        initiatePropertyExchange();
        return; // 不进入下一回合，等待交换完成
      case 'selectExchangePlayer':
        // 选择交换对象
        handlePropertyExchange(action.playerId);
        return; // 不进入下一回合，等待选择地产
      case 'selectOwnProperty':
        // 选择自己的地产
        handleSelectOwnProperty(action.cellIndex);
        return; // 不进入下一回合，等待选择对方地产
      case 'completeExchange':
        // 完成交换
        completePropertyExchange(action.ownCellIndex, action.targetCellIndex);
        break;
      case 'confirm':
      default:
        // 默认确认，进入下一回合
        nextTurn();
        break;
    }
  }
}